#include "Logger.hpp"
#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define KEY_PATH "/home/xj"
#define PROJ_ID 200644
#define SHM_SIZE 4096

Logger& Log = Logger::GetInstance();

key_t GetKey(){
    int key_ret = ftok(KEY_PATH, PROJ_ID);
    if(key_ret == -1){
        Log(Fatal, "Failed to get Key! erron: %s", errno);
        exit(1);
    }
    Log(Info, "Get Key successfully, key = 0x%x", key_ret);

    return key_ret;
}

int ShareMemHelper(int flag){
    key_t key_ret = GetKey();
    int shm_id = shmget(key_ret, SHM_SIZE, flag);
    if(shm_id == -1){
        Log(Fatal, "Failed to get share mem errno : %s", errno);
        exit(2);
    }
    Log(Info, "Get share men successfully, shm_id = %d", shm_id);

    return shm_id;
}

int CreateShareMem(){
    return ShareMemHelper(IPC_CREAT | IPC_EXCL | 0664);
}

int GetShareMem(){
    return ShareMemHelper(IPC_CREAT);
}